package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    /**
     * 员工登录验证
     * @param username
     * @param password
     * @return
     */
    @Override
    public Employee login(String username, String password) {
        //使用用户名,调用mapper查询员工
        LambdaQueryWrapper<Employee> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,username);
        Employee employee = employeeMapper.selectOne(wrapper);
        //得到查询结果,判断员工是否存在
        if (employee==null){
            return null;
        }
        //存在,就进行密码校验
        //对表现层提供的明文密码进行加密
        String md5Password = SecureUtil.md5(password);
        //加密后的密码和员工对象中的密码进行匹配,如果不行同,就返回null
        if (!md5Password.equals(employee.getPassword())){
            return null;
        }
        //如果匹配就返回员工对象
        return employee;
    }

    /**
     * 查询所有员工
     * @return
     */
    @Override
    public List<Employee> findAll(String name) {
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Employee::getName,name);
        List<Employee> employeeList = employeeMapper.selectList(wrapper);
        return employeeList;
    }

    /**
     * 添加员工
     * @param employee
     */
    @Override
    public void save(Employee employee) {
        //补全员工信息
        employee.setId(IdUtil.getSnowflake(1,1).nextId());
        employee.setStatus(1);
        employee.setPassword(SecureUtil.md5("123456"));
        employeeMapper.insert(employee);
    }

    /**
     * 修改员工信息,回显数据
     * @param id
     * @return
     */
    @Override
    public Employee findById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        return employee;
    }

    /**
     * 更新员工信息
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        //设置修改条件
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getId,employee.getId());
        employeeMapper.updateById(employee);
    }
}










































